<template>
  <view class="container">
    <view class="step-wrap">
      <ve-steps :list="stepList" :active="activeStepListIndex" />
    </view>
    <view class="order-relet-content" :style="{ 'padding-bottom': activeStepListIndex == 0 ? '130rpx' : '360rpx' }">
      <summary-info title="租赁信息" :summaryList="summaryLease" :defaultFold="false">
        <template #leasePeriod>
          <view class="lease-period">
            <view class="lease-period-val">{{ orderInfo.startTime ? `${orderInfo.startTime} - ${orderInfo.endTime}` : '-' }}</view>
            <view class="lease-period-rentdays" v-if="orderInfo.rentDays">租期：{{ orderInfo.rentDays }}</view>
          </view>
        </template>
      </summary-info>
      <ve-form :model="form" layout="vertical" :rules="rules" ref="formRef" v-show="activeStepListIndex == 0">
        <ve-card class="relet-info" title="续租信息">
          <ve-form-item prop="endTime" required label="续租后还车时间">
            <ve-date-picker v-model="form.endTime" :minDate="orderInfo.endTime" @confirm="calcRentDays" />
            <template #rightContent>
              <view class="rent-days"> 续租时长：{{ rentDays || '- 天' }} </view>
            </template>
          </ve-form-item>
          <ve-form-item label="续租备注" :borderBottom="false" labelPosition="top">
            <ve-input type="textarea" v-model="form.remark" :maxlength="200" />
          </ve-form-item>
        </ve-card>
      </ve-form>
      <!-- 费用信息 -->
      <view class="fee-pane-content" v-show="activeStepListIndex == 1">
        <ve-form :model="feeForm" ref="feeFormRef" layout="vertical" :rules="feeFormRules">
          <ve-card title="续租费用" fold>
            <template v-for="(item, index) in feeForm.orderFee" :key="index">
              <fee-pane
                :isReletOrder="true"
                :orderFormType="'reletOrder'"
                :orderFeeIndex="index"
                :inlineCard="true"
                :showViewPriceCalendarBtn="showViewPriceCalendarBtn"
                :disabledOnlineFee="orderInfo.orderSource == 1"
                @viewPriceCalendar="viewPriceCalendarFn"
                @feeChange="feeChangeFn"
              />
            </template>
          </ve-card>
        </ve-form>
      </view>
    </view>
    <!-- 二次确认 -->
    <ve-confirm titleText="请确认是否排车？" v-model="confirmVisible" @confirm="confirmSubmit">
      <view v-for="(it, i) in resultMsg" :key="i">{{ it }}</view>
    </ve-confirm>
    <footer-box id="footer-box">
      <block v-if="activeStepListIndex == 0">
        <ve-button size="long" type="primary" @click="stepClickFn">下一步 去完善费用信息</ve-button>
      </block>
      <template #extra v-if="activeStepListIndex == 1">
        <feeStatistic feeSummaryTitle="续租费用信息" :showOriginFeeStatics="true" :originSumInfo="originSumInfo" />
      </template>
      <block v-if="activeStepListIndex == 1">
        <ve-button type="plain" @click="stepClickFn">上一步</ve-button>
        <ve-button type="primary" :loading="okLoading" @click="submitFn">完成</ve-button>
      </block>
    </footer-box>
  </view>
</template>
<script setup name="ShortOrderReletOrder">
  import { ref, provide, computed, nextTick } from 'vue'
  import {
    computeRentDayAPI,
    getShortOrdrDetailsAPI,
    reletOrderAPI,
    calcPriceAPI,
    platoonCarCheckAPI,
    getShortOrdrFeeDetailAPI,
    inspectPrice,
  } from '@/api/order/sOrder'
  import summaryInfo from './components/summary-info.vue'
  import feePane from './components/order-fee/fee-pane.vue'
  import footerBox from './form/components/footerBox.vue'
  import feeStatistic from './components/order-fee/fee-statistic.vue'
  import {
    buildCostInfoParam,
    initFeeDetail,
    getStoreTemplateDetail,
    handleStoreTemplateDetail,
    getOrderFeeRules,
    handleAddserviceDefaultFee,
  } from './components/order-fee/fee-utils.js'
  import { decimalAddition } from '@/utils'
  import { buildTreeData, processTreeData } from './components/order-fee/fee-statistic.js'
  import useFormFold from '@/hooks/useFormFold'
  import dayjs from 'dayjs'
  import { onLoad } from '@dcloudio/uni-app'
  const { foldValidate } = useFormFold([])
  import useToast from '@/hooks/useToast'
  import { useLoadDataAndHotUpdateNavigateBack } from '@/hooks/useListNavigate'

  const form = ref({})
  const orderInfo = ref({})
  const orderId = ref()
  onLoad((options) => {
    orderId.value = options.id
    form.value = {
      id: orderId.value,
    }
    // 初始化
    init()
  })
  // 费用变化
  const feeChangeFn = (item, val, index) => {
    let feeDetailList = feeForm.value.orderFee[0].feeDetailList
    let option = feeDetailList[index].childrenList
    let itemName = item.itemName
    if (itemName == '日租价') {
      let target = option.find((item) => item.itemName == '车辆租金')
      if (target) target.amount = val * calcRate.value
    }
  }

  const stepList = ['续租信息', '续租费用信息']
  const activeStepListIndex = ref(0)

  // 处理默认值
  // 租赁周期限制最小时长 60 分钟
  const timeRangeValidator = (rule, value, callback) => {
    if (value) {
      let start = orderInfo.value.endTime
      let end = value
      if (start && end) {
        let diff = dayjs(end).diff(dayjs(start))
        if (diff < 60 * 60 * 1000) {
          callback('续租时长最短为1小时')
        }
      }
    }
    callback()
  }
  const rules = {
    endTime: [{ required: true, message: '请选择续租后还车时间' }, { validator: timeRangeValidator }],
  }

  // 表单规则
  const feeFormRules = computed(() => {
    return getOrderFeeRules(feeForm.value.orderFee)
  })

  const formRef = ref()
  provide('form', form)

  // 顶部统计信息
  const summaryLease = computed(() => {
    const orderInfoVal = orderInfo.value
    return [
      { label: '预计租赁周期', slotName: 'leasePeriod' },
      { label: '交车车牌号', value: orderInfoVal.carLicenseNo },
      { label: '预订车型', value: orderInfoVal.originalModelName },
      { label: '交车车型', value: orderInfoVal.carModelName },
      { label: '订单来源', value: orderInfoVal.orderSourceName },
    ]
  })

  const priceTemplateId = ref()
  const feeFormRef = ref()
  const feeForm = ref({
    randomKey: 0,
    orderFee: [
      {
        // 费用类型（线上费用|线下费用）
        feeType: 1,
        feeDetailList: [],
        priceTemplateId: priceTemplateId,
        feeDetailTypeList: ['basicFee', 'addServiceFee', 'preferentialFee', 'otherFee'],
      },
    ],
  })
  provide('feeForm', feeForm)

  // 初始化
  const cacheStoreTemplate = ref({})
  const init = () => {
    // 获取订单详情
    getShortOrdrDetailsAPI({ id: orderId.value }).then((res) => {
      const result = res.result
      orderInfo.value = result.orderInfo

      // 初始化续租后还车时间为当前结束时间 + 1 天
      let endTime = orderInfo.value.endTime
      if (endTime) {
        form.value.endTime = dayjs(endTime).add(1, 'day').format('YYYY-MM-DD HH:mm:ss')
      }

      // 读取门店模板配置
      getStoreTemplateDetail(orderInfo.value.siteId, 1, (storeTemplate, templateId) => {
        cacheStoreTemplate.value = storeTemplate
        let feeValue = feeForm.value
        initFeeDetail(feeValue, storeTemplate)
        // 更新费用模板 id
        priceTemplateId.value = templateId
        // 计算租期
        calcRentDays()
      })
    })
  }

  // 获取默认费用
  // 车型价格模板 id
  const priceModelId = ref()
  const calcRate = ref()
  // 是否显示价格日历
  const showViewPriceCalendarBtn = computed(() => {
    return !!priceModelId.value
  })
  const setDefaultFee = () => {
    const param = {
      id: form.value.id,
      siteId: orderInfo.value.siteId,
      modelId: orderInfo.value.originalModelId,
      endTime: form.value.endTime,
      type: 3,
    }
    calcPriceAPI(param).then((res) => {
      const { basePrice, otherPrice, rate } = res.result
      calcRate.value = rate
      if (basePrice) {
        priceModelId.value = basePrice.id
      } else {
        priceModelId.value = ''
      }
      let feeValue = feeForm.value
      let feeDetailList = feeValue.orderFee[0].feeDetailList
      // 处理增值服务费默认值
      handleAddserviceDefaultFee(feeDetailList, cacheStoreTemplate.value, rate)
      // 初始化其他费用
      feeDetailList.forEach((feeCategory) => {
        const { childrenList } = feeCategory
        // 默认系统计算的费用包含，基础费用，押金费用以及增值服务费中的例如上门取车费、夜间服务费等费用
        if (childrenList && childrenList.length > 0) {
          childrenList.forEach((feeItem) => {
            // 费用名称
            let feeName = feeItem.itemName
            // basicPrice 费用
            if (feeName == '日租价') {
              if (basePrice?.avgPrice >= 0) feeItem.amount = basePrice?.avgPrice
            }
            if (feeName == '手续费') {
              if (basePrice?.poundageAmount >= 0) feeItem.amount = basePrice?.poundageAmount
            }
            // otherPrice 费用
            if (otherPrice && otherPrice.length > 0) {
              let findIndex = otherPrice.findIndex((item) => item.itemName == feeName)
              if (findIndex >= 0) {
                let fee = otherPrice[findIndex]
                feeItem.statics = true
                if (fee?.amount >= 0) {
                  feeItem.amount = fee.amount
                }
              }
            }
          })
          childrenList.forEach((it) => {
            if (['手续费', '车辆租金', '基础保险'].includes(it.itemName)) {
              it.amount = it.amount > 0 ? it.amount : ''
            }
          })
        }
      })
      // 当没有下单车型时，此时费用计算不会计算出下述几种费用，此时需要手动补充费用，补充0
      if (!basePrice) {
        feeDetailList.forEach((feeCategory) => {
          const { childrenList } = feeCategory
          if (childrenList && childrenList.length > 0) {
            childrenList.forEach((feeItem) => {
              // 费用名称
              let feeName = feeItem.itemName
              // basicPrice 费用
              if (['手续费', '车辆租金', '基础保险'].includes(feeName)) {
                feeItem.amount = ''
              }
              if (['日租价'].includes(feeName)) {
                feeItem.amount = 0
              }
            })
          }
        })
      }
    })
  }
  // 计算租期
  const rentDays = ref()
  const calcRentDays = () => {
    let startTime = orderInfo.value.endTime
    let value = form.value.endTime
    if (value) {
      // 计算租期
      const param = {
        startTime: startTime,
        endTime: value,
        siteId: orderInfo.value.siteId,
      }
      computeRentDayAPI(param).then((res) => {
        let { days } = res.result
        if (days.indexOf('小时') >= 0 && days.indexOf('天') >= 0) {
          days = days.replace('天', ' 天 ').replace('小时', ' 小时')
        } else {
          days = days.replace('天', ' 天').replace('小时', ' 小时')
        }
        rentDays.value = days
      })
      setDefaultFee()
    } else {
      rentDays.value = undefined
    }
  }
  // 点击下一步
  const stepClickFn = () => {
    // 当前 step
    let currStep = activeStepListIndex.value
    // 切换到第二步
    if (currStep == 0) {
      formRef.value.validate((valid, errors) => {
        if (valid) {
          // 页面滚动到错误位置
          activeStepListIndex.value = 1
          scrollToTopFn()
          getPrevFeeInfo()
        } else {
          foldValidate(errors, true)
        }
      })
    } else {
      activeStepListIndex.value = 0
      scrollToTopFn()
    }
  }
  // 查看价格日历
  const viewPriceCalendarFn = () => {
    let start = dayjs(orderInfo.value.startTime).startOf('month').format('YYYY-MM-DD HH:mm:ss')
    uni.navigateTo({
      url: `/pages/order/price-calendar?priceModelName=${orderInfo.value.originalModelName}&priceModelId=${priceModelId.value}&start=${start}`,
    })
  }
  // 获取原费用信息
  const prevFeeForm = ref({})
  // 原费用合计
  const originSumInfo = ref({
    sum: 0,
    feeList: [],
  })
  const getPrevFeeInfo = () => {
    // 获取原费用信息
    getShortOrdrFeeDetailAPI({ id: orderId.value }).then((res) => {
      const result = res.result
      const orderFeeList = result.orderFeeList
      if (orderFeeList?.length > 0) {
        let rentFee = orderFeeList.find((item) => item.feeNameId == 1)
        prevFeeForm.value = {
          orderFee: [
            {
              // 费用类型（线上费用|线下费用）
              feeDetailList: [],
              feeDetailTypeList: ['basicFee', 'addServiceFee', 'preferentialFee', 'otherFee'],
            },
          ],
        }
        // 创建费用时的费用模板快照
        let priceTemplateSnapshot = rentFee.priceTemplateSnapshot
        // 解析后的费用模板
        let storeTemplate = null
        if (priceTemplateSnapshot) {
          priceTemplateSnapshot = JSON.parse(priceTemplateSnapshot)
          storeTemplate = handleStoreTemplateDetail(priceTemplateSnapshot)
        }
        initFeeDetail(prevFeeForm.value, storeTemplate)
        // 回显费用
        let feeDetailList = rentFee.feeDetailList
        let formfeeDetailList = prevFeeForm.value.orderFee[0].feeDetailList
        formfeeDetailList.forEach((formFeeDetailItem) => {
          let findResult = feeDetailList.find((item) => {
            let sameFeeCategory = item.feeCategory == formFeeDetailItem.feeCategory
            let sameFeeName = item.itemName == formFeeDetailItem.feeName
            return sameFeeCategory || sameFeeName
          })
          if (findResult) {
            formFeeDetailItem.categoryType = findResult.type
          } else {
            formFeeDetailItem.categoryType = 0
          }
          formFeeDetailItem.childrenList?.forEach((item) => {
            let findFeeDetail = findResult?.childrenList.find((feeDetailItem) => feeDetailItem.itemName == item.itemName)
            if (!findFeeDetail) {
              findFeeDetail = feeDetailList.find((feeDetailItem) => feeDetailItem.itemName == item.itemName)
            }
            if (findFeeDetail) {
              item.amount = findFeeDetail.amount
              item.id = findFeeDetail.id
              item.statics = true
            }
          })
        })

        let processedData = buildTreeData(prevFeeForm.value.orderFee)
        if (processedData) {
          processedData = processTreeData(processedData)
        }
        originSumInfo.value.feeList = processedData
        // 计算合计
        let sum = 0
        processedData.forEach((item) => {
          sum = decimalAddition(sum, item.value)
        })
        originSumInfo.value.sum = sum
      }
    })
  }
  // 页面滚动到顶部
  const scrollToTopFn = () => {
    uni.pageScrollTo({
      scrollTop: 0,
      duration: 200,
    })
  }
  // 续租
  const okLoading = ref(false)
  const reletFn = () => {
    let feeFormValue = feeForm.value
    let costInfo = buildCostInfoParam(feeFormValue)
    const param = {
      ...form.value,
      orderFee: {
        ...costInfo.orderFee[0],
        priceModelId: priceModelId.value,
      },
    }
    let beforeStatus = param.orderFee.feeDetailList.some((it) => {
      if (it.childrenList) {
        return it.childrenList.some((item) => {
          return item.amount === 0
        })
      } else {
        return it.amount === 0
      }
    })
    if (beforeStatus) {
      uni.showModal({
        title: '提示',
        content: '请注意，金额为0时不生成费项信息',
        success: function (res) {
          if (res.confirm) {
            toSubmitFn(param)
          }
        },
      })
    } else {
      toSubmitFn(param)
    }
  }
  const toSubmitFn = (param) => {
    okLoading.value = true
    reletOrderAPI(param)
      .then(() => {
        confirmVisible.value = false
        useToast({
          title: '续租成功',
        }).then(() => {
          useLoadDataAndHotUpdateNavigateBack()
        })
      })
      .catch(() => {
        okLoading.value = false
      })
  }
  // 排车校验
  const resultMsg = ref([])
  const confirmVisible = ref(false)
  const platoonCarVerify = (callback) => {
    const params = {
      refId: orderInfo.value.id,
      startTime: orderInfo.value.endTime,
      endTime: form.value.endTime,
      useType: 2,
      carId: orderInfo.value.carId,
    }
    platoonCarCheckAPI(params).then((res) => {
      let msgList = res.result.resultMsg || []
      if (msgList.length) {
        resultMsg.value = msgList
        confirmVisible.value = true
        return
      }
      callback && callback()
    })
  }
  // 二次询问确认
  const confirmSubmit = () => {
    if (orderInfo.value.orderSource == 2 && orderInfo.value.channelOrderMaintenance == 1) {
      orderConfirmFn()
    } else {
      reletFn()
    }
  }
  // 确认续租
  const submitFn = () => {
    feeFormRef.value.validate((valid, errors) => {
      if (valid) {
        platoonCarVerify(() => {
          confirmSubmit()
        })
      } else {
        // 页面滚动到错误位置
        foldValidate(errors, true)
      }
    })
  }
  // 自动维护的渠道订单
  const orderConfirmFn = () => {
    confirmVisible.value = false
    uni.showModal({
      title: '提示',
      content: '操作续租后，该笔订单不再自动同步渠道信息，需手动完成还车等操作，确认续租吗？',
      success: function (res) {
        if (res.confirm) {
          reletFn()
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  }
</script>
<style lang="less" scoped>
  .container {
    display: flex;
    flex-direction: column;
    background: #f7f8fa;
    .step-wrap {
      border-top: 2rpx solid #f7f8fa;
      background-color: #ffffff;
      z-index: 9;
      position: fixed;
      width: 100%;
      left: 0;
    }
    .order-relet-content {
      padding: 24rpx;
      padding-top: 178rpx;
    }
  }
  .lease-period-rentdays {
    font-size: 30rpx;
    color: #3072f6;
    margin-top: 8rpx;
  }
  .rent-days {
    font-size: 30rpx;
    text-align: right;
    color: #3072f6;
  }

  .fee-pane-content {
    /deep/ .ve-card-content {
      padding-bottom: 0;
    }
  }
  #footer-box {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    z-index: 999;
  }
</style>
